package com.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @author seven
 */
public class StringByteUtil {

    /**
     * byte[]转换16进制字符串
     *
     * @param data
     * @return
     */
    public String[] byteToStr(byte[] data) {
        if (data == null || data.length <= 0) {
            return null;
        }
        String[] arr = new String[data.length];
        for (int i = 0; i < data.length; i++) {
            String charAt = Integer.toHexString(data[i] & 0xFF).toUpperCase();
            arr[i] = charAt.length() <= 1 ? "0" + charAt : charAt;
        }
        return arr;
    }

    /**
     * 16进制转换为10进制
     *
     * @param data
     * @return String
     */
    public String sixteenToTenString(String data) {
        if (StringUtils.isEmpty(data)) {
            throw new NullPointerException();
        }
        Integer v = Integer.valueOf(data, 16);
        return v.toString();
    }

    /**
     * 16进制转换为10进制
     *
     * @param data
     * @return Integer
     */
    public Integer sixteenToTenInt(String data) {
        if (StringUtils.isEmpty(data)) {
            throw new NullPointerException();
        }
        return Integer.valueOf(data, 16);
    }

    /**
     * 16进制直接转换成为字符串(无需Unicode解码)
     * @param data
     * @return
     *
     */
    public String sixteenToStr(String data) {
        String str = "0123456789ABCDEF";
        char[] chars = data.toCharArray();
        byte[] bytes = new byte[data.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(chars[2 * i]) * 16;
            n += str.indexOf(chars[2 * i + 1]);
            bytes[i] = (byte)(n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * 16进制转double
     * @return
     */
    public Double sixteenToDouble(String data){
        return Double.longBitsToDouble(Long.parseLong(data,16));
    }

    /**
     * 16进制转
     * @param data
     * @return
     */
    public Float sixteenToFloat(String data){
        return Float.intBitsToFloat(Integer.parseInt(data,16));
    }

    /**
     * 16进制转long
     * @param data
     * @return
     */
    public Long sixteenToLong(String data){
        return Long.parseLong(data,16);
    }
    /**
     * 读取指定长度数据转换为字符串
     *
     * @param value
     * @param start
     * @param len
     * @return
     */
    public String copyOfRangeToJoin(String[] value, int start, int len) {
        if (start + len > value.length) {
            throw new IndexOutOfBoundsException();
        }
        if (len <= 0) {
            return "";
        }
        int end = start + len;
        return Arrays.stream(Arrays.copyOfRange(value, start, end)).collect(Collectors.joining());
    }

}
